<?php
Authenticate::requireAccounting();
$db = Db::getInstance();
$db->autocommit(false);
$pdo = Db::getPDO();
$pdo->beginTransaction();
try {
    if($_SERVER['REQUEST_METHOD'] == 'DELETE'){
        parse_str(file_get_contents("php://input"), $formData);
        Account::instance()->del($formData['id']);
        Payment::instance()->del(array('accountId'=> $formData['id']));
        Table::instanceTable('Invoice')->del(array('accountId'=> $formData['id']));
        Product::instance()->del($formData['id']);
        Topic::instance()->del($formData['id']);
        $db->commit();
        $pdo->commit();
        echo json_encode(array('success'=> true));
    }
    else if($_SERVER['REQUEST_METHOD'] == 'GET'){
        $account = Account::instance()->getOne($_GET['id']);
        if($account){
            unset($account['password']);
            echo json_encode($account);
        }
    }
    else if($_SERVER['REQUEST_METHOD'] == 'PUT'){
        parse_str(file_get_contents("php://input"), $formData);
        $id = $formData['id'];
        $editData = $formData;
        unset($editData['id']);

        $query = sprintf("SELECT * FROM Account WHERE email='%s' AND id!='%s'",
            $db->real_escape_string($formData['email']),
            $db->real_escape_string($id));

        $result = $db->query($query);
        if(!$result){
            throw new Exception($db->error);
        }
        if($result->num_rows != 0){
            throw new Exception('ห้าม Email ซ้ำกัน Account อื่น');
        }
        Account::instance()->edit($id, $editData);
        $db->commit();
        $pdo->commit();
        echo json_encode(array('success'=> true));
    }
    else if($_SERVER['REQUEST_METHOD'] == 'POST'){
        Account::instance()->add(array(
            'email'=> $_POST['email'],
            'phone'=> $_POST['phone'],
            'password'=> md5($_POST['password']),
            'name'=> $_POST['name'],
            'address'=> $_POST['address'],
            'peopleId'=> $_POST['peopleId'],
            'status'=> 1
        ));
        $db->commit();
        $pdo->commit();
        echo json_encode(array('success'=> true));
    }
    else if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
        parse_str(file_get_contents("php://input"), $formData);
        if($formData['operation'] == 'active'){
            Account::instance()->activeById($formData['id']);
            $db->commit();
            $pdo->commit();
            echo json_encode(array('success'=> true));
        }
    }
}
catch(Exception $ex){
    $pdo->rollBack();
    $db->rollback();
    echo json_encode(array('success'=> false, 'message'=> $ex->getMessage()));
    throw $ex;
}